from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler
from conf import settings


def custom_exception_handler(exc, context):
    """
    自定义异常处理方法
    """
    # 先调用REST_framework默认的异常处理方法获得标准错误响应对象
    response: Response = exception_handler(exc, context)
    if response is None:
        # 在DEBUG模式下不处理系统异常,如果处理后错误页面将变成标准格式
        if settings.DEBUG:
            raise exc
        res = {'msg': exc, 'code': 500, 'data': exc}
        return Response(res, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)  # 只有500这个状态码
    else:
        # msg = response.reason_phrase

        if "detail" in response.data:
            msg = response.data["detail"]
        elif "msg" in response.data:
            msg = response.data["msg"]
        else:
            msg = []
            for k, v in response.data.items():
                if isinstance(v, list):
                    msg.append(k + v[0])
        if isinstance(msg, list):
            msg = '、'.join(msg)
        res = {"msg": msg, "code": response.status_code}
        # res.update(response.data)

        return Response(res, status=response.status_code, exception=True)


